/*
 * @depends component.js, Panel.js
 */
QFinance.component.AccountsEditPanel = Ext.extend( QFinance.ui.Panel, {
    // Configuration
    autoLoadAccounts: true,
    canAddAccount: true,
    canEditAccount: true,
    canRemoveAccount: true,
	
    // Localization	
    addAccountText: 'Add',
    addAccountTooltipText: 'Add a new account',
    editAccountText: 'Edit',
    editAccountTooltipText: 'Edit account',
    removeAccountText: 'Remove',
    removeAccountTooltipText: 'Remove account',
    accountText: 'Account',
    bankNumberText: 'Bank number',
    bankAgencyText: 'Bank agency',
    bankAccoutText: 'Bank account',
    initialAmountText: 'Initial amount',
    accountTypeNameText: 'Type',
    removeQuestionTitle: 'Remove account',
    removeQuestionMsg: 'Would you like to remove selected accounts?',
    editInformationTitle: 'Edit account',
    editInformationMsg: 'Please select an account to edit.',
    removeInformationTitle: 'Remove account',
    removeInformationMsg: 'Please select an account to remove.',	
	
    // Components
    store: null,		
    grid: null,
    accountRecord: null,	
	
    constructor: function(config) {
        Ext.apply(this, config);
		
        this.createAccountRecord();
		
        this.store = new Ext.data.DirectStore({
            autoSave: false,
            autoLoad: false,
            idProperty: 'id',
            root: 'data',
            successProperty: 'success',
            paramsAsHash: false,    		
            api: {
                read: QFinance.Remoting.AccountsEditPanelAction.read,
                create: QFinance.Remoting.AccountsEditPanelAction.create,
                update: QFinance.Remoting.AccountsEditPanelAction.update,
                destroy: QFinance.Remoting.AccountsEditPanelAction.destroy
            },
            writer: new Ext.data.JsonWriter({
                encode: false,
                writeAllFields: true
            }),			
            fields: this.accountRecord,
            listeners: {
                scope: this,
                beforeload: function(store, options) {
                    store.id = this.getProcessStatusManager().start([this]);
                },				
                load: function(store, records, options) {
                    this.getProcessStatusManager().success(store.id);
                },
                beforewrite: function(  store, action, rs, options, arg ) {
                    store.id = this.getProcessStatusManager().start([this]);
                },
                write: function(  store, action, rs, options, arg ) {
                    this.getProcessStatusManager().success(store.id);
                },				
                exception: function(dataProxy, type, action, options, response, arg ) {
                    var message = '';
                    var where = '';
                    if (response.result) {
                        message = response.result.message;
                        if (response.result.type == 'exception')
                            where = response.result.where;
                    } else {
                        message = response.message;
                    }
                    this.getProcessStatusManager().success(this.store.id, message);                    
                    QFinance.service.DeveloperService.log('Store failure: ' + message + ' where\n' + where);					
                }
            }
        });
		
        this.addEvents([ 
            'close'
            ]);		
		
        QFinance.component.AccountsEditPanel.superclass.constructor.call(this);
    },
	
    initComponent: function() {		
        var topBarConfig = this.getTopBarConfig();		
        var topBar = new Ext.Toolbar(topBarConfig);
        var gridConfig = this.getGridConfig(topBar);
        this.grid = new Ext.grid.GridPanel(gridConfig);
				
        Ext.apply(this,{
            layout: 'fit',			
            items: [this.grid]
        });

        QFinance.component.AccountsEditPanel.superclass.initComponent.call(this);
    },
	
    createAccountRecord: function() {
        this.accountRecord = Ext.data.Record.create([{
            name: 'id',
            type: 'int'
        },{
            name: 'accountName'
        },{
            name: 'bankNumber'
        },{
            name: 'bankAccount'															
        },{
            name: 'accountType',
            type: 'int'
        },{
            name: 'accountTypeName'
        },{
            name: 'initialAmount',
            type: 'float'															
        },{
            name: 'bankAgency'
        }]);
    },
	
    getTopBarConfig: function() {
        var topBarConfig = [];
				
        if (this.canAddAccount) {
            topBarConfig.push({
                text: this.addAccountText,
                tooltip: this.addAccountTooltipText,
                iconCls: 'fugue-wallet--plus',
                scope: this,
                handler: function() {
                    var baseRecordConfig = {
                    }; 
										
                    var newAccount = new QFinance.component.AccountEditWindow({
                        ownerWindow: this.getOwnerWindow(),
                        record: new this.accountRecord(baseRecordConfig),
                        listeners: {
                            scope: this,
                            save: function( record ) {
                                this.store.add( record );
                                this.doSave();								
                            }
                        }
                    });
                    newAccount.show();
                }
            });
        }
		
        if (this.canEditAccount) {
            topBarConfig.push({
                text: this.editAccountText,
                tooltip: this.editAccountTooltipText,
                iconCls: 'fugue-wallet--pencil',
                scope: this,
                handler: function() {
                    var selectedRecord = this.grid.getSelectionModel().getSelected();
					
                    if (selectedRecord) {
                        var editAccount = new QFinance.component.AccountEditWindow({
                            ownerWindow: this.getOwnerWindow(),
                            record: selectedRecord,
                            isNew: false,
                            autoLoadRecord: true,							
                            listeners: {
                                scope: this,
                                save: function(record) {
                                    this.doSave();
                                }
                            }
                        });
                        editAccount.show();
                    } else {
                        var information = new QFinance.ui.MessageBox();
                        information.show({
                            title: this.editInformationTitle,
                            msg: this.editInformationMsg,
                            buttons: Ext.MessageBox.OK,
                            renderTo: this.body,
                            icon: Ext.MessageBox.INFO
                        });
                    }
                }
            });
        }
		
        if (this.canRemoveAccount) {
            topBarConfig.push({
                text: this.removeAccountText,
                tooltip: this.removeAccountTooltipText,
                iconCls: 'fugue-wallet--minus',
                scope: this,
                handler: function() {
                    var selectedRecords = this.grid.getSelectionModel().getSelections();
					
                    if (selectedRecords.length > 0) {
                        var question = new QFinance.ui.MessageBox();
                        question.show({
                            title: this.removeQuestionTitle,
                            msg: this.removeQuestionMsg,
                            buttons: Ext.MessageBox.YESNO,
                            scope: this,
                            fn: function(btn) {
                                if (btn == 'yes') {
                                    for (var i = 0; i < selectedRecords.length; i++)
                                        this.store.remove( selectedRecords[i] );
                                    this.doSave();
                                }								   
                            },
                            renderTo: this.body,
                            icon: Ext.MessageBox.QUESTION
                        });
                    } else {
                        var information = new QFinance.ui.MessageBox();
                        information.show({
                            title: this.removeInformationTitle,
                            msg: this.removeInformationMsg,
                            buttons: Ext.MessageBox.OK,
                            renderTo: this.body,
                            icon: Ext.MessageBox.INFO
                        });						
                    }
                }
            });
        }
		
        return topBarConfig;
    },
	
    getGridConfig: function(topBar) {
        var gridConfig = {
            store: this.store,			
            columns: [
            {
                id			: 'accountName',
                header		: this.accountText, 
                sortable	: true,
                dataIndex	: 'accountName'	            
            },{
                id			: 'bankNumber',
                header		: this.bankNumberText, 
                sortable	: true,
                dataIndex	: 'bankNumber',
                width		: 80
            },{
                id			: 'bankAgency',
                header		: this.bankAgencyText, 
                sortable	: true,
                dataIndex	: 'bankAgency',
                width		: 80
            },{
                id			: 'bankAccount',
                header		: this.bankAccoutText,
                sortable	: true,
                dataIndex	: 'bankAccount',
                width		: 80
            },{
                id			: 'initialAmount',
                header		: this.initialAmountText, 
                sortable	: true,
                dataIndex	: 'initialAmount',
                scope		: this,
                renderer: function(value, metaData, record, rowIndex, colIndex, store) {	            	
                    return '<span style="color:green;">' + QFinance.moneySymbol + ' ' + Ext.util.Format.number(value,QFinance.numberFormat) + '</span>';	            	
                },
                width		: 80	            
            },{
                id			: 'accountTypeName',
                header		: this.accountTypeNameText, 
                sortable	: true,
                dataIndex	: 'accountTypeName',
                width		: 50
            }],
            stripeRows: true,
            autoExpandColumn: 'accountName',
            sm: new Ext.grid.RowSelectionModel(),
            tbar: topBar,
            stateful: true,
            stateid: 'QFinance.component.AccountsEditPanel.grid'
        };
		
        return gridConfig;
    },
		
    doSave: function() {
        this.store.save();
    },
        
    autoLoadData: function() {
        if (this.autoLoadAccounts)
            this.load();
    },
	
    load: function() {
        this.store.load();
    }
});
Ext.reg('QFinance.component.AccountsEditPanel', QFinance.component.AccountsEditPanel);